;(function(Ext,metaData){
	Ext.Loader.setPath("FormFieldUtil",contextPath+"ui_tpl/FormFieldUtil.js");
	Ext.require("FormFieldUtil");
	var refMetaMap=metaData["refMetaMap"],
	refEnumMap=metaData["refEnumMap"],
	mainMetaId=metaData['id'],
	mainMeta=refMetaMap[mainMetaId],
	protoMetaId=mainMeta["meta"],
	protoMeta=refMetaMap[protoMetaId],
	fields=mainMeta["fields"],
	attrs=mainMeta["attrs"],
	action=attrs['action']||{type:"rest",url:"/meta/record/"+metaData["id"]},
	modelName=mainMeta["code"],
	modelFields=[],columns=[],validators={},
	typeMap={"1":"string","-5":"int","4":"int","12":"string","16":"boolean","91":"date","93":"date","97":"date"};
	Ext.iterate(fields,function(field,i){
		
		var type=field["type"],name=field["name"],f={name:name,type:typeMap[field["type"]]},
		attrs=field["attrs"],
		col={dataIndex:name,text:field["text"],menuDisabled:true},
		valid={};
		if(attrs["enums"]){
			col["renderer"]=(function(){
				var enums=attrs["enums"],vf=attrs["valueField"]||"code",df=attrs["displayField"]||"text";
				enums=enums.substring(enums.indexOf("$")+1);
				var enumData=refEnumMap[enums],remap={};
				var list=enumData["list"];
				Ext.iterate(list,function(n,i){
					remap[n[vf]]=n[df];
				});
				switch(type){
					case -5:
					case 4:
						return function(v){
							return remap[v+""];
						};
						break;
					default :
						return function(v){
							return remap[v];
						}
				}
			})();
		}else{
			switch(type){
			case -5:
			case 4:
				break;
			case 91:
				col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d');
				break;
			case 92:
				col["renderer"]=Ext.util.Format.dateRenderer('h:i:s');
				break;
			case 93:
				col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d h:i:s');
				col["width"]=150;
				break;
			}
		}
		
		modelFields.push(f);
		columns.push(col);
	});
	var startParam ="pageInfo.start",limitParam="pageInfo.limit",pageParam="pageInfo.page",
	sortParam="sortInfo.field",directionParam="sortInfo.direct",
	paramNames={
			startParam:startParam,
			limitParam:limitParam,
			pageParam:pageParam,
			sortParam:sortParam,
			directionParam:directionParam
			},
			extraParams={};
	
	extraParams[sortParam]=(attrs.idProperty||"id");
	extraParams[directionParam]="ASC";
	var proxy={
			url:action["url"],
			type:action["type"],
			extraParams: extraParams,
			reader: {  
                type: 'json',
                rootProperty: 'itemList',
                totalProperty: 'pageInfo.total'
            },
            simpleSortMode: true
		};
	Ext.apply(proxy,paramNames);
	Ext.define(modelName,{
		extend:"Ext.data.Model",
		idProperty:attrs["idProperty"]||"id",
		fields:modelFields,
		proxy:proxy
	});
	
	
	Ext.define('Ext.ux.SearchGrid',{
		extend:"Ext.container.Container",
		xtype:"searchgrid",
		layout:"border",
		requires: [
		        'Ext.toolbar.Paging',
		],
		initComponent:function(){
			var me=this;
			me.gridId="grid_"+metaData["id"];
			me.pagingtoolbarId="pageTool"+metaData["id"];
			Ext.apply(this,attrs);
			this.searchFields=attrs["searchFields"]||['name','text'];
			this.showColumns=attrs["showColumns"];
			var searchForm=this.searchForm=this.initSearchForm('north'),
			dataGrid=this.dataGrid=this.initDataGrid('center');
			this.items=[searchForm,dataGrid];
			this.callParent();
		},
		refreshGrid:function(){
			this.store.reload();
		},
		initGridStore:function(){
			var me=this,store=this.store=Ext.create('Ext.data.Store',{
				model:modelName,
				autoLoad:true
			});
			return store;
		},
		initTBar:function(){
			var me=this,
			tbar=this.tbar=[{
				text:"刷新",
				iconCls:"fa fa-refresh",
				handler:function(){
					me.refreshGrid();
				}
			},{
				text:"查看",
				iconCls:"fa fa-eye",
				handler:function(){
					
				}
			}];
		},
		initSearchForm:function(region){
			var me=this,searchItems=FormFieldUtil.getSearchFormFields(mainMetaId,metaData,me.searchFields),
			formConfig={
					xtype:'form',
					layout:"hbox",
					split:true,
					tbar:me['tbar'],
					scrollable:true,
					region:region,
					height:80,
					minHeight:50,
					width:'auto',
					bodyPadding:15,
					items:searchItems
			};
			searchItems.push({
				margin:'0 5 0 5',
				iconCls:"fa fa-search",
				xtype:'button',
				text:"搜索",
				handler:function(){
					var params=this.up('form').getValues();
					var proxy = me.store.getProxy(),
			       extraParams= proxy.extraParams;
					
					Ext.iterate(params,function(k,v,o){
						extraParams["filter."+k]=v||"";
					});
					var pagingtoolbar=Ext.getCmp(me.pagingtoolbarId);
					pagingtoolbar.moveFirst();
				}
			});
			searchItems.push({
				margin:'0 5 0 5',
				xtype:'button',
				iconCls:'fa fa-refresh',
				text:"重置",
				handler:function(){
					this.up('form').reset();
					var proxy = me.store.getProxy(),
				       extraParams= proxy.extraParams;
						Ext.iterate(extraParams,function(k,v,o){
							if(k.indexOf("filter.")>-1){
								extraParams[k]="";
							}
							
						});
						var pagingtoolbar=Ext.getCmp(me.pagingtoolbarId);
						pagingtoolbar.moveFirst();
				}
			});
			return formConfig;
		},
		initTBar:function(){
			var me=this,tbar=this.tbar=[];
		},
		initDataGrid:function(region){
			var me=this;
			
			this.initGridStore();
			this.initTBar();
			if(me.showColumns){
				Ext.iterate(columns,function(col,i){
					var name=col["dataIndex"];
					var exist=Ext.Array.contains(me.showColumns,name);
					col["hidden"]=!exist;
				});
			}
			
			var me=this,grid=this.gridPanel={
				xtype:"grid",
				minHeight:300,
				width:'auto',
				id:me.gridId,
				region:region,
				split:true,
				viewConfig: {
			        trackOver: false,
			        stripeRows: false,
			        enableTextSelection:true
			    },
			    store:me.store,
			    columns:columns,
				height:'auto',
				bbar: {
			        xtype: 'pagingtoolbar',
			        id:me.pagingtoolbarId,
			        displayInfo: true,
			        displayMsg: ' {0} - {1} 总数： {2}',
			        emptyMsg: "无数据",
			        store:me.store
			    }
			};
			return grid;
		}
	});
	
	Ext.application({
	    name: 'MyApp',
	    mainView:'Ext.ux.SearchGrid',
	    launch: function () {
	    }
	});
})(Ext,metaData);